package com.cy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cy.common.entity.Result;
import com.cy.common.exception.CommonException;
import com.cy.common.util.HttpRequest;
import com.cy.common.util.IdWorker;
import com.cy.common.util.JwtUtils;
import com.cy.entity.User;
import com.cy.entity.vo.UserVo;
import com.cy.service.LoginService;
import com.cy.service.UserService;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * @Author : 残影
 * @Date: 2021-02-22 11:10
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Value("${wx.appid}")
    private String addId ;
    @Value("${wx.secret}")
    private  String secret;
    @Value("${wx.authentication}")
    private  String authentication;
    @Value("${wx.session.url}")
    private  String sessionUrl;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private UserService userService;
    @Override
    public Result getAppletLogin(String code, UserVo userVo) {
        // 设置访问微信服务器的参数
        String params = "appid=" + addId
                + "&secret=" + secret
                + "&js_code=" + code
                + "&grant_type=" + authentication;
        // 返回的数据是 json 格式的字符串
        String result = HttpRequest.sendGet(sessionUrl, params);

        //解析json字符串
        Gson gson = new Gson();
        HashMap map = gson.fromJson(result, HashMap.class);
        System.out.println(map);
        if (ObjectUtils.isEmpty(map)) {
            throw new CommonException("微信授权失败");
        }
        if (!ObjectUtils.isEmpty(map.get("errcode")) || !ObjectUtils.isEmpty(map.get("errmsg"))) {
            throw new CommonException("微信授权失败");
        }
        String openid = (String) map.get("openid");
        if (StringUtils.isEmpty(openid)) {
            throw new CommonException("微信授权失败");
        }
        User user = new User();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        user = userService.getOne(queryWrapper);
        //查询数据库当前用用户是否曾经使用过微信登录
        if (ObjectUtils.isEmpty(user)) {
            User user1 = new User();
            BeanUtils.copyProperties(userVo, user1);
            user1.setId(idWorker.nextId());
            user1.setHaveUserInfo("1");
            user1.setOpenid(openid);
            userService.save(user1);
        }
        String token = "";
        if (!ObjectUtils.isEmpty(userVo)) {
            token = JwtUtils.getJwtToken(user.getId(), user.getNickName());
        }
        return Result.ok().put("token",token).put("user",user);
    }
}
